#include "Node.h"

int Node::mFrame = 0;


Node::Node(){ 
	mName = new string(""); 
	mModel = NULL; 
	mJoints = new vector<Node*>();
	mChannelValue = new float[mMaxChannels]; 
	mChannels = NULL;
	mFrames = new vector<vector<float>*>(); 
	mOffset = new D3DXVECTOR3();
}

void Node::Update(float pElapsedTime){
	for(int i =0; i < mJoints->size();i++){
		mJoints->at(i)->Update(pElapsedTime);
	}
}

void Node::Draw(LPDIRECT3DDEVICE9 d3ddev, LPD3DXMATRIXSTACK pStack){


	mModel->GetPos()->x = mOffset->x;
	mModel->GetPos()->y = mOffset->y;
	mModel->GetPos()->z = mOffset->z;

	for(int i =0; i < mNumOfChannels; i++){
		int channel = mChannels[i];

		switch(channel){
			case (int)zRot:
				mModel->GetRot()->z = mFrames->at(mFrame)->at(i);
				break;
			case (int)xRot:
				mModel->GetRot()->x = mFrames->at(mFrame)->at(i);
				break;
			case (int)yRot:
				mModel->GetRot()->y = mFrames->at(mFrame)->at(i);
				break;
			case (int)zTrans:
				mModel->GetPos()->z = mFrames->at(mFrame)->at(i);
				break;
			case (int)xTrans:
				mModel->GetPos()->x = mFrames->at(mFrame)->at(i);
				break;
			case (int)yTrans:
				mModel->GetPos()->y = mFrames->at(mFrame)->at(i);
				break;
		}
	}
	
	pStack->Push();
	D3DXMATRIX* mPos =  new D3DXMATRIX();
	D3DXMATRIX* YRot =  new D3DXMATRIX();
	D3DXMATRIX* XRot =  new D3DXMATRIX();
	D3DXMATRIX* ZRot =  new D3DXMATRIX();
	D3DXMATRIX* matrixFinal =  new D3DXMATRIX();


	D3DXMatrixRotationY( YRot, D3DXToRadian( mModel->GetRot()->y ) );
	D3DXMatrixRotationX( XRot, D3DXToRadian( mModel->GetRot()->x ) );
	D3DXMatrixRotationZ( ZRot, D3DXToRadian( mModel->GetRot()->z ) );
	::D3DXMatrixTranslation( mPos,mModel->GetPos()->x,mModel->GetPos()->y,mModel->GetPos()->z );

	matrixFinal = &(*(XRot) * *(YRot) * *(ZRot) * *(mPos));

	//pStack->Translate(mModel->GetPos()->x,mModel->GetPos()->y,mModel->GetPos()->z);
	//pStack->RotateYawPitchRoll(mModel->GetRot()->y,mModel->GetRot()->x,mModel->GetRot()->z);
	
	//pStack->MultMatrix(mModel->GetTransMatrix());

	pStack->MultMatrixLocal(matrixFinal);

	ModelPrimitive* mPrim = (ModelPrimitive*)mModel;
	//mModel->Draw(d3ddev);
	d3ddev->SetTransform(D3DTS_WORLD, pStack->GetTop());
	d3ddev->SetMaterial(mPrim->GetMaterial());
	mPrim->GetMeshPrim()->DrawSubset(0);

	for(int i =0; i < mJoints->size();i++){
		mJoints->at(i)->Draw(d3ddev,pStack);
	}
	
	pStack->Pop();
	//::ID3DXMatrixStack::Pop();
}